import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Repository } from 'typeorm';
import { User } from './user.mysql.entity';
import { Department } from '../department/entities/department.entity';

@Injectable()
export class UserService {
  constructor(
    @Inject('USER_REPOSITORY')
    private userRepository: Repository<User>,
    @Inject('DEPARTMENT_REPOSITORY')
    private departmentRepository: Repository<Department>,
  ) {}

  async create(createUserDto) {
    const dep = await this.departmentRepository.findOne({
      where: { id: createUserDto.departmentId },
    });
    return this.userRepository.save({
      ...createUserDto,
      department: dep,
    });
  }

  findAll() {
    return this.userRepository.find({ relations: ['department'] });
  }

  findOne(id: number) {
    return this.userRepository.findOneBy({ id });
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    // 创建一个不包含departmentId和department字段的新对象
    const { departmentId, department, ...updateData } = updateUserDto;
    
    // 如果updateUserDto中包含departmentId，则需要先获取department实体
    if (updateUserDto.departmentId) {
      const dep = await this.departmentRepository.findOne({
        where: { id: updateUserDto.departmentId },
      });
      
      // 只有当部门存在时才更新部门信息
      if (dep) {
        // 更新用户信息，包括关联的部门
        return this.userRepository.update({ id }, {
          ...updateData,
          department: dep,
        });
      } else {
        // 如果部门不存在，则只更新其他字段
        return this.userRepository.update({ id }, updateData);
      }
    }
    
    // 如果没有departmentId，则直接更新（排除department字段）
    return this.userRepository.update({ id }, updateData);
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }
}
